<template>
  <div class="app-container">
    <div class="block">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="listQuery.name" size="mini" placeholder="分类名称" />
        </el-col>
        <el-col :span="6">
          <el-button type="success" size="mini" icon="el-icon-search" @click.native="search">查找</el-button>
          <el-button type="success" size="mini" icon="el-icon-plus" @click.native="handleAdd">添加
          </el-button>
        </el-col>
      </el-row>
      <br>
    </div>
    <el-table
      :data="list"
      style="width: 100%"
    >
      <el-table-column label="分类名称">
        <template v-slot="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="分类编码">
        <template v-slot="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.validStatus == 'INVALID'"
            size="mini"
            type="success"
            @click="handleValid(scope.row.id)"
          >启用
          </el-button>
          <el-button
            v-if="scope.row.validStatus == 'VALID'"
            size="mini"
            type="danger"
            @click="handleInValid(scope.row.id)"
          >禁用
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="saveRules(scope.row)"
          >关联规则
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top:15px"
      align="right"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-size="listQuery.limit"
      :total="total"
      @current-change="fetchPage"
      @prev-click="fetchPrev"
      @next-click="fetchNext"
    />

    <el-dialog :visible.sync="addFormVisible" title="添加模板项">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="模板项名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入模板项名称" clearable :style="{width: '100%'}" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入编码" clearable :style="{width: '100%'}" />
        </el-form-item>
        <el-form-item label="输入类型" prop="inputType">
          <el-select v-model="formData.inputType" placeholder="请选择输入类型" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in inputTypeOptions"
              :key="index"
              :label="item.name"
              :value="item.code"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="值类型" prop="valueType">
          <el-select v-model="formData.valueType" placeholder="请选择值类型" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in valueTypeOptions"
              :key="index"
              :label="item.name"
              :value="item.code"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联字典" prop="dictId">
          <el-select v-model="formData.dictId" placeholder="请选择关联字典" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in dictIdOptions"
              :key="index"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="占位符" prop="placeholder">
          <el-input v-model="formData.placeholder" placeholder="请输入占位符" clearable :style="{width: '100%'}" />
        </el-form-item>
        <el-form-item label="排序号" prop="sortNum">
          <el-input-number v-model="formData.sortNum" placeholder="排序号" :step="1" />
        </el-form-item>
        <el-form-item label="是否必填" prop="requireFlag" required>
          <el-switch v-model="formData.requireFlag" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="扩展属性">
          <el-button @click="addKeyValue" >添加键值对</el-button> <el-button @click="removeKeyValue" >移除键值对</el-button>
          <div v-for="(kv,i) in formData.extList" :key="i" style="margin-top: 5px;">
            <el-row :gutter="18">
              <el-col :span="6">
                <el-input v-model="kv.k" placeholder="键" />
              </el-col>
              <el-col :span="6">
                <el-input v-model="kv.v" placeholder="值" />
              </el-col>
              <el-col :span="6">
                <el-input v-model="kv.l" placeholder="标签" />
              </el-col>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" clearable :style="{width: '100%'}" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="assignFormVisible" title="关联规则">
      <el-form ref="itemForm" :model="itemFormData" :rules="itemRules" size="medium" label-width="100px">
        <el-form-item label="关联规则" prop="ruleIds">
          <el-select v-model="itemFormData.ruleIds" multiple placeholder="请选择关联的规则" :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in itemIdsOptions"
              :key="index"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="assignFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAssign">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  findByPage,
  valid,
  invalid,
  create,
  inputType,
  valueType,
  assignRules
} from '@/api/template/templateItem'
import { findAllByCondition } from '@/api/template/selectDict'
import { findAll } from '@/api/template/mockRule'
export default {
  components: {},
  inheritAttrs: false,
  props: [],
  data() {
    return {
      addFormVisible: false,
      assignFormVisible: false,
      listQuery: {
        page: 1,
        limit: 10,
        name: ''
      },
      total: 0,
      list: null,
      listLoading: true,
      formData: {
        name: undefined,
        code: undefined,
        inputType: undefined,
        valueType: undefined,
        dictId: undefined,
        placeholder: undefined,
        sortNum: undefined,
        requireFlag: 0,
        remark: undefined,
        extList: []
      },
      itemFormData: {
        itemId: '',
        ruleIds: undefined
      },
      itemRules: {
        ruleIds: [{
          required: true,
          message: '请选择关联的规则项',
          trigger: 'change'
        }]
      },
      itemIdsOptions: [],
      rules: {
        name: [{
          required: true,
          message: '请输入模板项名称',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '请输入编码',
          trigger: 'blur'
        }],
        inputType: [{
          required: true,
          message: '请选择输入类型',
          trigger: 'change'
        }],
        // valueType: [{
        //   required: true,
        //   message: '请选择值类型',
        //   trigger: 'change'
        // }],
        dictId: [],
        placeholder: [{
          required: true,
          message: '请输入占位符',
          trigger: 'blur'
        }],
        sortNum: [{
          required: true,
          message: '排序号',
          trigger: 'blur'
        }],
        remark: [{
          required: true,
          message: '请输入备注',
          trigger: 'blur'
        }]
      },
      inputTypeOptions: [],
      valueTypeOptions: [],
      dictIdOptions: []
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      const queryData = {
        'bean': {
          'name': this.listQuery.name
        },
        'pageSize': this.listQuery.limit,
        'page': this.listQuery.page
      }
      findByPage(queryData).then(response => {
        this.list = response.result.list
        this.listLoading = false
        this.total = response.result.total
      })
    },
    search() {
      this.fetchData()
    },
    reset() {
      this.listQuery.name = ''
      this.fetchData()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleValid(id) {
      valid(id).then(response => {
        this.$message.success({
          type: 'success',
          message: '启用成功'
        })
        this.fetchData()
      })
    },
    handleInValid(id) {
      invalid(id).then(response => {
        this.$message.success({
          type: 'success',
          message: '禁用成功'
        })
        this.fetchData()
      })
    },
    fetchNext() {
      this.listQuery.page = this.listQuery.page + 1
      this.fetchData()
    },
    fetchPrev() {
      this.listQuery.page = this.listQuery.page - 1
      this.fetchData()
    },
    fetchPage(page) {
      this.listQuery.page = page
      this.fetchData()
    },
    changeSize(limit) {
      this.listQuery.limit = limit
      this.fetchData()
    },
    handleUpdate() {

    },
    saveRules(row) {
      this.itemFormData.itemId = row.id
      findAll().then(response => {
        this.itemIdsOptions = response.result
      })
      this.assignFormVisible = true
    },
    handleAdd() {
      this.addFormVisible = true
      const queryData = {
        'name': '',
        'code': ''
      }
      findAllByCondition(queryData).then(response => {
        this.dictIdOptions = response.result
      })
      inputType().then(response => {
        this.inputTypeOptions = response.result
      })
      valueType().then(response => {
        this.valueTypeOptions = response.result
      })
    },
    close() {
      this.addFormVisible = false
    },
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        create(JSON.stringify(this.formData)).then(response => {
          this.$message.success({
            type: 'success',
            message: '保存成功'
          })
          this.fetchData()
        })
        this.close()
      })
    },
    addKeyValue() {
      this.formData.extList.push({ 'k': '', 'v': '', 'l': '' })
    },
    removeKeyValue() {
      this.formData.extList.pop()
    },
    submitAssign() {
      this.$refs['itemForm'].validate(valid => {
        if (!valid) return
        assignRules(JSON.stringify(this.itemFormData)).then(response => {
          this.$message.success({
            type: 'success',
            message: '保存成功'
          })
          this.fetchData()
        })
        this.assignFormVisible = false
      })
    }
  }
}
</script>
